{% from 'assess/sidebar/tri_state_filter.html' import tri_state_filter %}
{% set base_url = routes.base_route %}
{% set selected_groups = request.args.getlist('group') %}
{% set selected_sources = request.args.getlist('source') %}
{% set selected_tags = request.args.getlist('tags') %}
{% set current_search = request.args.get('search', '') %}
{% set current_limit = request.args.get('limit', 20) %}
{% set current_sort = request.args.get('sort', '') %}
{% set current_preset = request.args.get('range', '') %}
{% set time_from = request.args.get('timefrom', '') %}
{% set time_to = request.args.get('timeto', '') %}
{% set highlight = current_user.profile.highlight | default(false) %}
{% set show_week_chart = current_user.profile.show_charts %}
{% set compact_view = current_user.profile.compact_view %}
{% set read_filter = request.args.get('read', '') %}
{% set important_filter = request.args.get('important', '') %}
{% set in_report_filter = request.args.get('in_report', '') %}
{% set relevant_filter = request.args.get('relevant', '') %}
{% set cybersecurity_filter = request.args.get('cybersecurity', '') %}
{% set sort_choices = sort_choices | default([
  {'label': 'Newest first', 'value': 'date_desc'},
  {'label': 'Oldest first', 'value': 'date_asc'},
  {'label': 'Most relevant', 'value': 'relevance'},
  {'label': 'Most recent', 'value': 'updated_desc'},
  {'label': 'Least recent', 'value': 'updated_asc'}
]) %}
{% set quick_ranges = quick_ranges | default([
  {'label': 'Shift', 'value': 'shift'},
  {'label': 'Week', 'value': 'week'},
  {'label': '24h', 'value': '24h'}
]) %}
{% set tri_state_filters = [
  {'name': 'read', 'label': 'Read', 'value': read_filter},
  {'name': 'important', 'label': 'Important', 'value': important_filter},
  {'name': 'in_report', 'label': 'In Reports', 'value': in_report_filter},
  {'name': 'important', 'label': 'Impact', 'value': relevant_filter}
] %}

<script type="text/javascript">
const classNames = {
  containerOuter: ['choices', '!bg-base-200'],
  containerInner: ['choices__inner', '!bg-base-200'],
  input: ['choices__input', '!bg-base-200'],
  inputCloned: ['choices__input--cloned', '!bg-base-200'],
  list: ['choices__list', '!bg-base-200'],
  itemSelectable: ['choices__item--selectable', '!bg-primary-300'],
  itemChoice: ['choices__item--choice', '!bg-base-200', '!truncate', '!w-54'],
  selectedState: ['is-selected', '!bg-primary'],
};

const choicesConfig = {
  itemSelectText: '✓',
  appendGroupInSearch: true,
  classNames: classNames
}

if (typeof htmx !== 'undefined' && htmx.onLoad) {
  htmx.onLoad(function (elt) {
    initChoices('source-filter', 'sources', choicesConfig);
    highlightSearch({{ current_search | tojson }});
  });
} else {
  initChoices('source-filter', 'sources', choicesConfig);
  highlightSearch({{ current_search | tojson }});
}

function highlightSearch(searchTerm) {
  const term = typeof searchTerm === 'string' ? searchTerm : '';
  if ({{ highlight | tojson }} && term.trim().length > 0) {
    console.log("Highlighting search term: ", searchTerm);
    highlightSearchTerm({ search: term, selector: ".highlight"});
  }
}

document.addEventListener('htmx:afterSwap', function (event) {
  if (event.target && event.target.id === 'assess') {
    const searchInput = document.getElementById('story_search');
    if (searchInput) {
      highlightSearch(searchInput.value || '');
    }
  }
});

</script>

<div class="p-4 space-y-4">
  <form id="assess-sidebar"
        hx-get="{{ base_url }}"
        hx-target="#assess"
        hx-swap="outerHTML"
        hx-push-url="true"
        hx-trigger="change from:form, keyup changed delay:500ms from:input, search from:input">
    <section class="space-y-3">
      <div class="flex items-center justify-between">
        <h3 class="text-sm font-semibold uppercase tracking-wide text-base-content/60">Search &amp; Scope</h3>
        <a href="https://taranis.ai/docs/assess/#details"
           target="_blank"
           rel="noopener"
           class="link link-hover text-xs text-base-content/60 inline-flex items-center">
          help
          {{ heroicon_outline('arrow-top-right-on-square', class='h-3 w-3') }}
        </a>
      </div>

      <label class="input input-bordered input-sm flex items-center gap-2">
        {{ heroicon_outline('magnifying-glass', class='h-4 w-4 text-base-content/70') }}
        <input type="search"
               id="story_search"
               oninput="this.name = this.value ? 'search' : '';"
               value="{{ current_search }}"
               {% if current_search %}name="search"{% endif %}
               placeholder="Search stories"
               class="grow"
               autocomplete="off"
               @keydown.window.prevent.ctrl.k="$el.focus()"
               hx-trigger="keyup changed delay:500ms, search">
        <span class="text-xs">
          <kbd class="kbd kbd-xs text-base-content">ctrl+k</kbd>
        </span>
      </label>
      {% include 'assess/sidebar/tags_select.html' %}
    </section>

    {% include 'assess/sidebar/source_select.html' %}

    <div class="divider text-xs">Filter</div>
    {# djlint: off #}
    <section class="space-y-4"
             x-data='{
               clearTimeFilters() {
                 const timeFrom = this.$refs.timeFrom;
                 const timeTo = this.$refs.timeTo;
                 if (timeFrom) {
                   timeFrom.value = "";
                   timeFrom.removeAttribute("name");
                 }
                 if (timeTo) {
                   timeTo.value = "";
                   timeTo.removeAttribute("name");
                 }
                 if (this.$refs.rangeRadios) {
                   this.$refs.rangeRadios.querySelectorAll("input").forEach((radio) => {
                     radio.checked = false;
                   });
                 }
               }
             }'>
    {# djlint:on #}
    <button type="button"
            class="btn btn-outline btn-sm mb-2 w-full"
            title="Clear time filters"
            hx-get="{{ base_url }}"
            hx-params="remove:timefrom,timeto,range"
            hx-target="#assess"
            hx-swap="outerHTML"
            @click="clearTimeFilters()">{{ heroicon_mini('x-mark', class='h-4 w-4') }} Clear time filters</button>
    <div class="mt-2 flex w-full flex-wrap gap-2" role="radiogroup" aria-label="Time presets" x-ref="rangeRadios">
      {% for preset in quick_ranges %}
        {% set input_id = 'quick-range-' ~ preset.value %}
        <label class="cursor-pointer">
          <span class="label-text text-sm">{{ preset.label }}</span>
          <input id="{{ input_id }}"
                 type="radio"
                 name="range"
                 value="{{ preset.value }}"
                 class="radio"
                 hx-trigger="change"
                 {% if current_preset == preset.value %}checked{% endif %}>
        </label>
      {% endfor %}
    </div>
    <div class="grid grid-cols-1 gap-3">
      <label class="input w-full p-1">
        <span class="label text-xs font-medium text-base-content/70 pr-1 mr-1">From</span>
        <input type="datetime-local"
               x-ref="timeFrom"
               value="{{ time_from }}"
               {% if time_from %}name="timefrom"{% endif %}
               onchange="this.name = this.value ? 'timefrom' : ''"
               class="input-bordered input-xs -ml-3"
               hx-trigger="change delay:250ms">
      </label>
      <label class="input w-full p-1">
        <span class="label text-xs font-medium text-base-content/70 pr-1 mr-1">To</span>
        <input type="datetime-local"
               x-ref="timeTo"
               value="{{ time_to }}"
               {% if time_to %}name="timeto"{% endif %}
               onchange="this.name = this.value ? 'timeto' : ''"
               class="input-bordered input-xs -ml-3"
               hx-trigger="change delay:250ms">
      </label>
    </div>
  </section>

  <div class="divider text-xs">Status</div>
  <section class="space-y-3">
    {% for item in tri_state_filters %}{{ tri_state_filter(item) }}{% endfor %}
    <label class="select w-full">
      <span class="label">Cybersecurity</span>
      <select {% if cybersecurity_filter %}name="cybersecurity"{% endif %}
              onchange="this.name = this.value ? 'cybersecurity' : ''"
              class="select select-bordered select-sm"
              hx-trigger="change">
        <option value="" {% if cybersecurity_filter in ['', None] %}selected{% endif %}>Any</option>
        {% for option in ['yes', 'no', 'mixed', 'incomplete'] %}
          <option value="{{ option }}" {% if cybersecurity_filter == option %}selected{% endif %}>{{ option|capitalize }}</option>
        {% endfor %}
      </select>
    </label>
  </section>

  <div class="divider text-xs">Sort</div>
  <section>
    <label class="select w-full">
      <span class="label">Sort</span>
      <select {% if current_sort %}name="sort"{% endif %}
              onchange="this.name = this.value ? 'sort' : ''"
              class="select select-bordered select-sm"
              hx-trigger="change">
        {% for option in sort_choices %}
          <option value="{{ option.value }}" {% if option.value == current_sort %}selected{% endif %}>{{ option.label }}</option>
        {% endfor %}
      </select>
    </label>
  </section>
</form>

<div class="divider text-xs">Display</div>
<section class="space-y-2">
  <label class="label cursor-pointer justify-start gap-3">
    <input type="checkbox"
           class="checkbox checkbox-sm"
           name="highlight"
           value="true"
           hx-post="{{ url_for('user.settings') }}"
           hx-trigger="change"
           hx-on::after-swap="window.location.reload()"
           {% if highlight %}checked{% endif %}>
    <span class="label-text">Highlight searchterms</span>
  </label>
  <label class="label cursor-pointer justify-start gap-3">
    <input type="checkbox"
           class="checkbox checkbox-sm"
           name="compact_view"
           value="true"
           hx-post="{{ url_for('user.settings') }}"
           hx-trigger="change"
           hx-on::after-swap="window.location.reload()"
           {% if compact_view %}checked{% endif %}>
    <span class="label-text">Compact view</span>
  </label>
</section>

<div class="space-y-3">
  <a href="{{ base_url }}?reset=true" class="btn btn-primary btn-sm w-full" @keyup.ctrl.escape.prevent.window="$el.click()">
    {{ heroicon_outline('arrow-path', class='h-4 w-4') }}
    Reset filters
    <span class="text-xs">
      <kbd class="kbd kbd-xs text-base-content">ctrl+esc</kbd>
    </span>
  </a>
  <a class="btn btn-secondary btn-sm w-full" href="{{ url_for('assess.create_news_item', news_item_id='0') }}">
    {{ heroicon_outline('pencil-square', class='h-4 w-4') }}
    Create new item
  </a>
</div>

{% include "partials/keyboard_hint.html" %}
</div>
